import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:speed_random/core/config/app_config.dart';
import 'package:speed_random/global_data.dart';


var wsLogger ;
var wsIsTest = false;
var wsIsTestInit = false;

/// 初始化ws
Future<void> wsPrintInit(String url) async{
  if(wsIsTestInit){
    return;
  }
  wsLogger.disconnect();
  wsIsTestInit = true;
  await EasyLoading.show(status: 'wsPrintInit...');
  wsLogger = WebSocketLogger(url);
  await wsLogger.connect();
  wsIsTest = true;
  wsIsTestInit = false;
  EasyLoading.dismiss();
  EasyLoading.showSuccess('wsPrintInit success');
}


wsPrint ( message,{String type = '',String bm = ''}) async{

  if(kDebugMode){
    print('wsPrint $message');
  }
  if(!wsIsTest){
    return;
  }

  if(bm == ''){
    bm = globalData.appName+"_"+AppConfig.current.flavors;
  }
  wsLogger.sendLog(type, bm, message.toString());
  //print("ws 发送");
  // 当不再需要时
  //wsLogger.disconnect();
}

/// ws://192.168.3.20:8080/ws
/// 发送格式 {"t":"2222","b":"bbbbb","m":"mmmmmm"}
/// 创建一个通用提交的日志方法使用 webSocket 提交 需要有断开重连接等
///
///
///
///
class WebSocketLogger {
  final String _url;
  WebSocketChannel? _channel;
  bool _isConnected = false;
  bool _shouldReconnect = true;
  int _reconnectDelay = 1000; // 初始重连延迟1秒

  WebSocketLogger(this._url);

  Future<void> connect() async {
    try {
      _channel = WebSocketChannel.connect(Uri.parse(_url));
      _isConnected = true;
      _reconnectDelay = 3000; // 连接成功后重置重连延迟

      _channel!.stream.listen(
        (message) {
          //print('Received: $message');
        },
        onError: (error) {
          print('WebSocket error: $error');
          _handleDisconnection();
        },
        onDone: () => _handleDisconnection(),
      );
    } catch (e) {
      print('Connection error: $e');
      _handleDisconnection();
    }
  }

  void _handleDisconnection() {
    _isConnected = false;
    if (_shouldReconnect) {
      _reconnect();
    }
  }

  void _reconnect() async {
    await Future.delayed(Duration(milliseconds: _reconnectDelay));
    _reconnectDelay = (_reconnectDelay * 2).clamp(1000, 30000); // 指数退避，最大30秒
    print('Attempting to reconnect...');
    connect();
  }

  void sendLog(String type, String body, String message) {
    if (!_isConnected) {
      print('Not connected, cannot send message');
      return;
    }

    final logData = {
      't': type,
      'b': body,
      'm': message,
    };

    try {
      _channel!.sink.add(jsonEncode(logData));
    } catch (e) {
      print('Error sending message: $e');
      _handleDisconnection();
    }
  }

  void disconnect() {
    _shouldReconnect = false;
    _channel?.sink.close();
    _isConnected = false;
  }
}

